import { message, type UploadProps } from 'ant-design-vue';

import {Apis} from '#/api';

export class FileUploader {
  fileList = [] as UploadProps['fileList'];
  remove: UploadProps['onRemove'] = (file) => {
    if (this.fileList) {
      const index = this.fileList.indexOf(file);
      const newFileList = [...this.fileList];
      newFileList.splice(index, 1);
      this.fileList = newFileList;
    }
  };
  select = async (fileUuids: string): Promise<UploadProps['fileList']> => {
    return new Promise<UploadProps['fileList']>((resolve, reject) => {
      Apis.attachment
        .get_list({
          params: { uuid: fileUuids },
        })
        .then((data) => {
          const files = [] as UploadProps['fileList'];
          for (const element of data.rows) {
            files?.push({
              uid: element.fileUuid,
              name: element.fileName,
              status: 'done',
              url: element.fileUrl,
            });
          }
          resolve(files);
        })
        .catch((error) => {
          reject(error);
        });
    });
  };

  upload = async (files?: UploadProps['fileList'], data?: any) => {
    return new Promise<void>(async (resolve, reject) => {
      if (this.fileList) {
        const formData = new FormData();

        if (data && Object.keys(data).length > 0) {
          Object.keys(data).forEach((key) => {
            formData.append(key, data[key]);
          });
        }

        const file = files || this.fileList;
        const alreadyUploaded = [] as string[];
        file.forEach((file: UploadProps['fileList'][number]) => {
          if (file.originFileObj) {
            formData.append('files', file.originFileObj as any);
          } else {
            alreadyUploaded.push(file.uid);
          }
        });
        this.uploading = true;

        // You can use any AJAX library you like
        try {
          this.fileList = [];
          this.uploading = false;
          let files = [];
          for (const element of alreadyUploaded) {
            files.push({
              fileUuid: element,
            });
          }

          const filesCount = formData.getAll('files').length;
          if (filesCount > 0) {
            const data = await Apis.attachment.post_uploads({
              data: formData,
            });
            files = files.concat(data.rows);
            message.success('上传成功.');
          }
          resolve(files || []);
        } catch {
          this.uploading = false;
          reject();
          message.error('上传失败.');
        } finally {
          this.uploading = false;
        }
      }
      reject();
    });
  };

  uploading = false;

  constructor(params: any) {}
}
